﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Blue.ResourceManager;
using System.IO;
using EngineOfEvermore.Editor.Common.Controls;

namespace EngineOfEvermore.Editor.Common
{
    public interface IResourceReferenceUpdater
    {
        String Message { get; }
        HashSet<String> ResourceExtensions { get; }
        int ResourceCount { get; }

        void Init( String oldResourceName, String newResourceName );

        String CurrentResourceName { get; }
        void ProcessCurrentResource();
    }

    public static class ResourceReferenceUpdater
    {
        static List<IResourceReferenceUpdater> _updaterList = 
            new List<IResourceReferenceUpdater>();
        static String _oldResourceName;
        static String _newResourceName;
        static ResourceReferenceUpdaterForm _updaterForm = new ResourceReferenceUpdaterForm();

        public static void AddUpdater(IResourceReferenceUpdater updater)
        {
            Debug.Assert( updater != null );
            Debug.Assert( !_updaterList.Contains( updater ) );

            _updaterList.Add( updater );
        }

        public static void Initialize()
        {
            ResourceManager.ResourceRenamed += _resourceRenamed;
        }

        static void _resourceRenamed( object sender, ResourceRenamedEventArgs e )
        {
            _oldResourceName = e.OldName;
            _newResourceName = e.NewName;

            _updaterForm.ShowDialog();
        }

        internal static void _run()
        {
            Debug.Assert( Path.GetExtension( _oldResourceName ) == 
                Path.GetExtension( _newResourceName ) );

            String ext = Path.GetExtension( _oldResourceName );

            var updaters = 
                _updaterList
                .Where( u => u.ResourceExtensions.Contains( ext ) )
                .ToArray();
            
            for ( int i = 0; i < updaters.Length; ++i )
            {
                _updaterForm.CurrentResourceUpdaterMessage = 
                    "(" + (i+1) + "of " + updaters.Length + "): " +
                    updaters[i].Message;

                updaters[i].Init( _oldResourceName, _newResourceName );

                _updaterForm.ProgressBar.Minimum = 0;
                _updaterForm.ProgressBar.Maximum = updaters[i].ResourceCount;

                int resourceIndex = 0;

                while ( updaters[i].CurrentResourceName != null )
                {
                    _updaterForm.CurrentResourceName = updaters[i].CurrentResourceName;

                    updaters[i].ProcessCurrentResource();

                    _updaterForm.ProgressBar.Value = ++resourceIndex;
                }
            }
        }
    }
}
